package com.imaker.webview.webview

import android.content.Context
import android.text.TextUtils
import android.util.AttributeSet
import android.util.Log
import android.webkit.JavascriptInterface
import com.google.gson.Gson
import com.imaker.webview.WebCommandDispatcher
import com.imaker.webview.bean.JsParam
import com.imaker.webview.callback.WebViewCallBack
import com.imaker.webview.webset.DefaultWebChromeClient
import com.imaker.webview.webset.DefaultWebSetting
import com.imaker.webview.webset.DefaultWebViewClient

/**
 * @author : dly on 2023/4/26
 *
 * desc :
 */
class BaseWebView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : com.tencent.smtt.sdk.WebView(context, attrs, defStyleAttr) {


    init {
        WebCommandDispatcher.instance.initAidlConnection(context)
        DefaultWebSetting.getSetting(this)
        addJavascriptInterface(this, "mywebview")
    }

    fun initWebClient(webViewCallBack: WebViewCallBack){
        webViewClient = DefaultWebViewClient(webViewCallBack)
        webChromeClient = DefaultWebChromeClient(webViewCallBack)
    }

    @JavascriptInterface
    fun takeNativeAction(jsParam: String?) {
        if (!TextUtils.isEmpty(jsParam)) {
            val jsParamObject: JsParam = Gson().fromJson(jsParam, JsParam::class.java)
            WebCommandDispatcher.instance.executeCommand(
                jsParamObject.name, Gson().toJson(
                    jsParamObject.param
                ), this
            )
        }
    }


    fun handleCallback(callbackname: String, response: String?) {
        if (!TextUtils.isEmpty(callbackname) && !TextUtils.isEmpty(response)) {
            post {
                val jscode = "javascript:myjs.callback('$callbackname',$response)"
                Log.d("xxxxxx", jscode)
                evaluateJavascript(jscode, null)
            }
        }
    }
}